from datetime import date, timedelta
from calendar import monthrange
from models import db, Holiday


def GetMonthRange(year, month):
    days = monthrange(year, month)[1]
    month_start_date = date(year, month, 1)
    month_end_date = month_start_date + timedelta(days - 1)
    return (month_start_date, month_end_date)


def GetWorkdays(year, month):
    days = monthrange(year, month)[1]
    month_start_date = date(year, month, 1)
    month_end_date = month_start_date + timedelta(days - 1)

    holidays = [
        day
        for (day,) in (
            db.session.query(Holiday.date)
            .filter(Holiday.date >= month_start_date)
            .filter(Holiday.date <= month_end_date)
            .filter(Holiday.isworkday == False)
            .all()
        )
    ]

    holiday_paybacks = [
        day
        for (day,) in (
            db.session.query(Holiday.date)
            .filter(Holiday.date >= month_start_date)
            .filter(Holiday.date <= month_end_date)
            .filter(Holiday.isworkday == True)
            .all()
        )
    ]

    workdays = []
    weekends = []

    for i in range(days):
        day = month_start_date + timedelta(i)
        weekday = day.weekday()
        if weekday < 5:
            workdays.append(day)
        else:
            weekends.append(day)

    workdays = set(workdays).difference(set(holidays)).union(set(holiday_paybacks))
    weekends = set(weekends).union(set(holidays)).difference(set(holiday_paybacks))

    workdays = sorted(list(workdays))
    weekends = sorted(list(weekends))

    return (workdays, weekends)


def GetStandWorkdays(year, month):
    workdays, _ = GetWorkdays(year, month)
    days = len(workdays)
    hours = days * 8
    return (days, hours)


if __name__ == "__main__":
    for i in range(1, 13):
        print(GetStandWorkdays(2020, i))

